package com.caimiao.miao.http.rxjava.transformer;

import com.caimiao.miao.bean.Response;
import com.caimiao.miao.http.retorfit.HttpConfig;
import com.caimiao.miao.http.rxjava.exception.ApiException;
import com.caimiao.miao.http.rxjava.exception.LocalException;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;

public class ResponseTransformer {

    /*data一般返回null，不关心data的类型*/
    public static <T> ObservableTransformer<Response, T> handleResult2() {
        return upstream -> upstream
                .onErrorResumeNext(new ErrorResumeFunction())
                .flatMap(new ResponseFunction());
    }

    /*需要解析data*/
    public static <T> ObservableTransformer<Response<T>, T> handleResult() {
        return upstream -> upstream
                .onErrorResumeNext(new ErrorResumeFunction<>())
                .flatMap(new ResponseFunction<>());
    }

    /*非服务器产生的异常，比如本地无无网络请求，Json数据解析错误等等。*/
    private static class ErrorResumeFunction<T> implements Function<Throwable, ObservableSource<? extends Response<T>>> {
        @Override
        public ObservableSource<? extends Response<T>> apply(Throwable throwable) throws Exception {
            return Observable.error(LocalException.handleException(throwable));
        }
    }

    /*服务其返回的数据解析，正常服务器返回数据和服务器可能返回的exception*/
    private static class ResponseFunction<T> implements Function<Response<T>, ObservableSource<T>> {

        @Override
        public ObservableSource<T> apply(Response<T> tResponse) throws Exception {
            int code = tResponse.getState();
            String msg = tResponse.getMsg();
            if (code == HttpConfig.STATE_SUCCESS) {
                return Observable.just(tResponse.getData());
            } else {
                return Observable.error(new ApiException(code, msg));
            }
        }
    }
}
